package com.dyh.quickdemozwei.util;

import com.alibaba.fastjson.JSONObject;
import org.junit.Test;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;

public class DesUtil {
	
    /**
     * 加密
     * @param data
     * @param sKey
     * @return
     */
    public static byte[] encrypt(byte[] data, String sKey) {
    	try{
    		SecureRandom random = new SecureRandom();
    		DESKeySpec desKey = new DESKeySpec(sKey.getBytes());
    		//创建一个密匙工厂，然后用它把DESKeySpec转换成
    		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    		SecretKey securekey = keyFactory.generateSecret(desKey);
    		//Cipher对象实际完成加密操作
    		Cipher cipher = Cipher.getInstance("DES");
    		//用密匙初始化Cipher对象
    		cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
    		//现在，获取数据并加密
    		//正式执行加密操作
    		return cipher.doFinal(data);
    		}catch(Throwable e){
    		e.printStackTrace();
    		}
    		return null;
    }

    /**
     * 解密
     * @param src
     * @param sKey
     * @return
     * @throws Exception
     */
    public static byte[] decrypt(byte[] src, String sKey) throws Exception {
    	// DES算法要求有一个可信任的随机数源
    	SecureRandom random = new SecureRandom();
    	// 创建一个DESKeySpec对象
    	DESKeySpec desKey = new DESKeySpec(sKey.getBytes());
    	// 创建一个密匙工厂
    	SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    	// 将DESKeySpec对象转换成SecretKey对象
    	SecretKey securekey = keyFactory.generateSecret(desKey);
    	// Cipher对象实际完成解密操作
    	Cipher cipher = Cipher.getInstance("DES");
    	// 用密匙初始化Cipher对象
    	cipher.init(Cipher.DECRYPT_MODE, securekey, random);
    	// 真正开始解密操作
    	return cipher.doFinal(src);
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
    
    /**
     * 加密入口
     * @param srcStr
     * @param charset
     * @param sKey
     * @return
     */
    public static String desEncrypt(String srcStr, Charset charset, String sKey) {
        byte[] src;
		try {
			src = srcStr.getBytes("utf-8");
	        byte[] buf = DesUtil.encrypt(src, sKey);
//	        return new String(Base64.encodeBase64String(buf));
	        return parseByte2HexStr(buf);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
    }

    /**
     * 解密入口
     *
     * @param hexStr
     * @param sKey
     * @return
     * @throws Exception
     */
    public static String desDecrypt(String hexStr, Charset charset, String sKey) throws Exception {
            byte[] src = parseHexStr2Byte(hexStr);
            byte[] buf = DesUtil.decrypt(src, sKey);
            return new String(buf, charset);
    }
    
//    public static void main(String[] args){
//    	String password = "appKey24725513appSecret5abb403a7971ad730639f3ebfa1894ec";
//    	String a = "shop苏州乐贝母婴专营";
//    	System.out.println(Md5Util.md5(password));
//    	String e = DesUtil.desEncrypt(a, Charset.forName("Utf-8"), Md5Util.md5(password));
//    	System.out.println(e);
//    }



    @Test
    public void testDe(){
        String state = "7B2273686F704E69636B223A2237303634363433333332333433383337333233363338333933323333222C226275223A22363837343734373037333341324632463646364437333736333237333739364536333245364336353731363536353245363336463644324636463644373332443733373936453633324636463644373335333739364536333246373336383646373032463633364636343635222C227369676E223A22443037303730423434443646413044313836303433373942463142313537444541373443413043414245394234323545222C2273797374656D54797065223A224F4D535F4F5554222C22616374696F6E223A22414444222C22704964223A3130313530342C2275756964223A223938663030346630323730356139343135353631333432306636623464396364222C22757365724964223A323536303331302C22706C6174666F726D223A2250494E44554F44554F222C2273686F70506C6174666F726D223A2250494E44554F44554F227D";

        String res = new String(DesUtil.parseHexStr2Byte(state), StandardCharsets.UTF_8);

        /*new String(DesUtil.parseHexStr2Byte(checkJson.getString("shopNick")), Charset.forName("utf-8"));*/
        System.out.println();
    }

    @Test public void testEn(){
        String str  = "{\"shopNick\":\"7064643332343837323638393233\",\"bu\":\"68747470733A2F2F6F6D73763273796E632E6C657165652E636F6D2F6F6D732D73796E632F6F6D7353796E632F73686F702F636F6465\",\"sign\":\"D07070B44D6FA0D18604379BF1B157DEA74CA0CABE9B425E\",\"systemType\":\"OMS_OUT\",\"action\":\"ADD\",\"pId\":101504,\"uuid\":\"98f004f02705a94155613420f6b4d9cd\",\"userId\":2560310,\"platform\":\"PINDUODUO\",\"shopPlatform\":\"PINDUODUO\"}";

        String state =  DesUtil.parseByte2HexStr(str.getBytes(StandardCharsets.UTF_8));

        System.out.println();
    }


    @Test
    public void testDe2(){
        String state = "68747470733A2F2F6F6D73763273796E632E6C657165652E636F6D2F6F6D732D73796E632F6F6D7353796E632F73686F702F636F6465";

        String res = new String(DesUtil.parseHexStr2Byte(state), StandardCharsets.UTF_8);

        /*new String(DesUtil.parseHexStr2Byte(checkJson.getString("shopNick")), Charset.forName("utf-8"));*/
        System.out.println();

        //https://omsv2sync.leqee.com/oms-sync/omsSync/shop/code
    }

    @Test public void testDex3(){
        JSONObject jo = new JSONObject();
        jo.put("shopNick","DYH测试用");

        System.out.println();
    }


}
